

import Docxtemplater from 'docxtemplater';
import { saveAs } from 'file-saver';
import PizZip from 'pizzip';
// import { Notification } from '@arco-design/web-vue';

// const docxUrl = "https://mp-9043bfed-8555-4e29-a9de-971bf3048fef.cdn.bspapp.com/bbb.docx"
// const data = {
//     fileName: "xxx的认购书",
//     dong: '#12',
//     danyuan: '2:',
//     mianji: 222,
//     total: 2000000,
//     price: 1000,
//     userlist: [{ name: "张三", phone: 15903627013 }, { name: "张三2", phone: 15903627014 }, { name: "张三3", phone: 15903627015 }, { name: "张三4", phone: 15903627016 }]
// };
async function exportDocx(docxUrl, data,location=false) {

    try {
        let template = ""
        if (!location) {
            template = await fetchDocxFromUrl(docxUrl)
        } else {
            //读取word模板
            const reader = new FileReader();
            reader.readAsArrayBuffer(docxUrl);
            await new Promise((resolve) => {
                reader.onload = resolve;
            });
            //
            template = reader.result;
        }


        const zip = new PizZip(template);
        const doc = new Docxtemplater();
        doc.loadZip(zip);
        doc.render(data);
        const output = doc.getZip().generate({ type: 'blob' });
        const fileName = data['fileName'] + '.docx';
        // 使用FileSaver.js文件保存生成的文档
        const blob = new Blob([output], {
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        });

        // window.open(URL.createObjectURL(blob));
        // 保存到本地
        saveAs(blob, fileName);
//         Notification.success({
//         title: '以保存到本地',
//         content: '请确认后打印',
//       })
        
        // printLocalFile(blob);

        return true
    } catch (err) {
        console.log('错处了', err)
    }
}


// 记载模板数据
async function fetchDocxFromUrl(url) {
    try {
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        // 将响应的数据流转换为ArrayBuffer
        const arrayBuffer = await response.arrayBuffer();
        return arrayBuffer;
    } catch (error) {
        console.error('从网络地址读取.docx文件时出错：', error);
        throw error;
    }
}
// 导入FileSaver.js

// ...

// 将Blob保存到本地文件
// saveAs(blob, fileName);

// 打印本地文件
function printLocalFile(blob) {
    if (blob.size > 0 && blob.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
        console.log('dddddd')
        // Blob对象有效
    } else {
        console.error('生成的Blob对象无效。');
    }
    const fileReader = new FileReader();

    fileReader.onload = function (e) {

        const printWindow = window.open('', '', 'width=800,height=600');
        const fileContent = e.target.result;
        // 在新窗口中创建一个临时的HTML文档
        const tempDocument = printWindow.document;
        tempDocument.open();
        tempDocument.write('<html><head><title>Print Document</title></head><body>');
        // 将Word文档的内容插入到新窗口的HTML中
        tempDocument.write('<embed width="100%" height="100%" src="data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,' + btoa(fileContent) + '" type="application/vnd.openxmlformats-officedocument.wordprocessingml.document"/>');
        // 关闭HTML文档
        tempDocument.write('</body></html>');
        tempDocument.close();
        // 打印新窗口中的文档
        printWindow.print();
        printWindow.onafterprint = function () {
            printWindow.close();
        };
    };

    // 读取Blob内容
    fileReader.readAsBinaryString(blob);
}

// 调用打印函数

export {
    exportDocx
}
